package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.DimUtil;
import com.atguigu.gmall.realtime.utils.PhoenixUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.util.Collection;
import java.util.Set;

/**
 * @author Felix
 * @date 2023/6/7
 * 将维度流中的数据写到Phoenix对应的表中
 */
public class DimSinkFunction implements SinkFunction<JSONObject> {
    @Override
    public void invoke(JSONObject jsonObj, Context context) throws Exception {
        //{"tm_name":"苹果11","sink_table":"dim_base_trademark","id":2}
        String sinkTable = jsonObj.getString("sink_table");
        // {"tm_name":"苹果11","id":2}
        jsonObj.remove("sink_table");

        String type = jsonObj.getString("type");
        jsonObj.remove("type");

        //upsert into 表空间.表名 (a,b,d) values(aa,bb,cc);
        Set<String> keys = jsonObj.keySet();
        Collection<Object> values = jsonObj.values();

        //拼接upsert语句
        String upsertSql = "upsert into " + GmallConfig.PHOENIX_SCHEMA + "." + sinkTable
            + " (" + StringUtils.join(keys, ",") + ") values('" + StringUtils.join(values, "','") + "')";
        System.out.println("向Phoenix表中插入数据的SQL:" + upsertSql);

        PhoenixUtil.executeSql(upsertSql);

        //如果维度数据发生了变化，将Redis中缓存的数据删除掉
        if("update".equals(type)){
            DimUtil.deleteCached(sinkTable,jsonObj.getString("id"));
        }
    }
}
